<?php
/**     
  *
  * Copyright (c) 2009, Persistent Systems Limited
  *
  * Redistribution and use, with or without modification, are permitted 
  *  provided that the following  conditions are met:
  *   - Redistributions of source code must retain the above copyright notice, 
  *     this list of conditions and the following disclaimer.
  *   - Neither the name of Persistent Systems Limited nor the names of its contributors 
  *     may be used to endorse or promote products derived from this software 
  *     without specific prior written permission.
  *
  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" 
  * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, 
  * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 
  * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR 
  * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, 
  * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, 
  * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; 
  * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, 
  * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR 
  * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, 
  * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  */

/**
 * File path for AtomParser.php
 */
require_once 'classes/AtomParser.php';
/**
 * SalesOrderModel Class
 * @access public
 */
class SalesOrderModel
{
	/** 
     * Class constructor.
	 * @access public
	 */
	public function __construct(){}
	
	/**
	 * Function to get sales Order Data
	 * @access public
	 *
	 * @param integer $salesPersonId Sales Persion Id
	 * @param integer $productId Product Id
	 * @param integer $regionId Region Id
	 * @return array $salesOrderArr Array of result data and error message if any
	 */
	public function getSalesOrderData($salesPersonId = '0', $productId = '0', $regionId = '0')
	{
		global $httpRequestObj;

		$salesOrderArr = array();
		$requestInfoArr = array();
		$qryString = "";

		try{

			if ($salesPersonId !="" && $salesPersonId > 0 ){
				$qryString .= "/salespersonid/".$salesPersonId.'/';
			}
			if ($productId != "" && $productId > 0){
				$qryString .= "/productid/".$productId.'/';
			}
			if ($regionId != "" && $regionId > 0){
				$qryString .= "/regionid/".$regionId.'/';
			}
			$url = SALES_ORDERS_SERVICE_URL.$qryString;
			$httpVerb = 'GET';
			
			//$headerValue = "WRAPv0.8" . " " . urldecode($_SESSION['token']); 
      $token =  "WRAP" . " " . 'access_token="' . urldecode($_SESSION['token']) . '"';
      $headerValue = $token; 
			$head['X-Authorization'] = $headerValue;
			
			$requestInfoArr['http_method']  = $httpVerb;
			$requestInfoArr['url']  = $url; 
			if(!empty($head)){
				foreach($head as $key => $value){
					$requestInfoArr[$key]  = urlencode($value);
				}
			}
			
			//Write Audit Log Details
			LoggerClass::writeLogEntry(REQUEST_TO_SALESDASHBOARD_SERVICE.'-'.GET_SALESDATA, $requestInfoArr);
			
			$salesOrdersFeedData = $httpRequestObj->sendRequest($httpVerb, $url ,array(), $head);
			
			$httpCode = $salesOrdersFeedData['http_code'];
			$response = $salesOrdersFeedData['response'];
			
			//Write Audit Log Details
			LoggerClass::writeLogEntry(RESPONSE_FROM_SALESDASHBOARD_SERVICE.'-'.GET_SALESDATA, $response);
			
			if ($httpCode == '200'){
				$salesOrdersObj = new AtomParser($response);
				$salesOrderArr['result']= $salesOrdersObj->parseString();
			} else {
				$salesOrderArr['error'] = 'Error Code '.$httpCode.':'.getStatusCodeMessage($httpCode).' for getting all sales orders data';
			}

		} catch (Exception $e){
			throw($e);

		}
		return $salesOrderArr;
	}
	/**
	 * Function to add sales Order Data
	 * @access public
	 * @param array $postFieldData Sales Order Details
	 * @return array $result Array of result data and error message if any
	 */
	public function addSalesOrder($postFieldData)
	{
		global $httpRequestObj;

		$requestInfoArr = array();

		try{
			$data['productid'] = $postFieldData['lstProduct'];
			$data['orderqty'] = $postFieldData['txtProductQty'];
			$data['salespersonid'] = $_SESSION['salesPersionID'];
			
			$url = CREATE_ORDER_SERVICE_URL;
			$httpVerb = 'POST';
			
			//$headerValue = "WRAPv0.8" . " " . urldecode($_SESSION['token']); 
      $token =  "WRAP" . " " . 'access_token="' . urldecode($_SESSION['token']) . '"';
      $headerValue = $token; 
			$head['X-Authorization'] = $headerValue;
			
			$requestInfoArr['http_method']  = $httpVerb;
			$requestInfoArr['url']  = $url; 
			if(!empty($head)){
				foreach($head as $key => $value){
					$requestInfoArr[$key]  = urlencode($value);
				}
			}
			
			if(!empty($data)){
				foreach($data as $key => $value){
					$requestInfoArr[$key]  = $value;
				}
			}

			//Write Audit Log Details
			LoggerClass::writeLogEntry(REQUEST_TO_SALESDASHBOARD_SERVICE.'-'.ADD_SALES_ORDER, $requestInfoArr);
			
			$salesOrdersFeedData = $httpRequestObj->sendRequest($httpVerb, $url,$data, $head);
			$httpCode = $salesOrdersFeedData['http_code'];
			
			//Write Audit Log Details
			LoggerClass::writeLogEntry(RESPONSE_FROM_SALESDASHBOARD_SERVICE.'-'.ADD_SALES_ORDER, $httpCode);
			
			if($httpCode == '201'){
				$result['result'] = true;
			} else {
				$result['error'] = 'Error Code '.$httpCode.':'.getStatusCodeMessage($httpCode).' for add new sales order';
			}
		} catch(Exception $e){
			throw($e);
		}
		return $result;
	}
	/**
	 * Function to get Sales Order data
	 * @access public
	 * @param integer $salesOrderId Sales Order Id
	 * @return array $orderDataArr Array of result data and error message if any
	 */
	public function getSalesOrderDetails($salesOrderId)
	{
		global $httpRequestObj;

		$orderDataArr = array();
		$requestInfoArr = array();
		try{
			$url = ORDER_INFO_SERVICE_URL.$salesOrderId."/";
			$httpVerb = 'GET';
			
			//$headerValue = "WRAPv0.8" . " " . urldecode($_SESSION['token']); 
      $token =  "WRAP" . " " . 'access_token="' . urldecode($_SESSION['token']) . '"';
      $headerValue = $token; 
			$head['X-Authorization'] = $headerValue;
			
			$requestInfoArr['http_method']  = $httpVerb;
			$requestInfoArr['url']  = $url; 
			if(!empty($head)){
				foreach($head as $key => $value){
					$requestInfoArr[$key]  = urlencode($value);
				}
			}
			
			//Write Audit Log Details
			LoggerClass::writeLogEntry(REQUEST_TO_SALESDASHBOARD_SERVICE.'-'.EDIT_SALES_ORDER, $requestInfoArr);
			

			$salesOrderData = $httpRequestObj->sendRequest($httpVerb, $url ,array(), $head);
			
			$httpCode = $salesOrderData['http_code'];
			$response = $salesOrderData['response'];
			
			//Write Audit Log Details
			LoggerClass::writeLogEntry(RESPONSE_FROM_SALESDASHBOARD_SERVICE.'-'.EDIT_SALES_ORDER, $response);
			
			if ($httpCode == '200'){		
				$regionObj = new AtomParser($response);
				$orderDataArr['result'] = $regionObj->parseString();
				
			} else {
				$orderDataArr['error'] = 'Error Code '.$httpCode.':'.getStatusCodeMessage($httpCode).' for edit sales order';
			}
			
		} catch(Exception $e){
			throw($e);
		}
		return $orderDataArr;
	}
	/**
	 * Function to get Sales Order data
	 * @access public
	 * @param array $postFieldData Sales Order details
	 * @return array $result Array of result data and error message if any
	 */
	public function updateSalesOrder($postFieldData)
	{
		global $httpRequestObj;

		$requestInfoArr = array();

		try{
			$data['salesorderid']  = $postFieldData['salesorderid'];
			$data['productid']     = $postFieldData['lstProduct'];
			$data['orderqty']      = $postFieldData['txtProductQty'];
			$data['salespersonid'] = $_SESSION['salesPersionID'];
			
			$url = UPDATE_ORDER_SERVICE_URL;
			$httpVerb = 'PUT';
			
			//$headerValue = "WRAPv0.8" . " " . urldecode($_SESSION['token']); 
      $token =  "WRAP" . " " . 'access_token="' . urldecode($_SESSION['token']) . '"';
      $headerValue = $token; 
			$head['X-Authorization'] = $headerValue;

			$requestInfoArr['http_method']  = $httpVerb;
			$requestInfoArr['url']  = $url; 
			if(!empty($head)){
				foreach($head as $key => $value){
					$requestInfoArr[$key]  = urlencode($value);
				}
			}
			if(!empty($data)){
				foreach($data as $key => $value){
					$requestInfoArr[$key]  = $value;
				}
			}
			//Write Audit Log Details
			LoggerClass::writeLogEntry(REQUEST_TO_SALESDASHBOARD_SERVICE.'-'.UPDATE_SALES_ORDER, $requestInfoArr);
			
			$salesOrderData = $httpRequestObj->sendRequest($httpVerb, $url, $data, $head);
			
			$httpCode = $salesOrderData['http_code'];

			//Write Audit Log Details
			LoggerClass::writeLogEntry(RESPONSE_FROM_SALESDASHBOARD_SERVICE.'-'.UPDATE_SALES_ORDER, $httpCode);
			
			if ($httpCode == '201'){
				$result['result'] = true;
			} else {
				$result['error'] = 'Error Code '.$httpCode.':'.getStatusCodeMessage($httpCode).' for update order';
			}

		} catch(Exception $e){
			throw($e);
		}
		return $result;
	}
	/**
	 * Function to validate Sales Order Form data for add/edit order
	 * @access public
	 * @param array $postData Sales Order details
	 * @return array $result Array of error message if any
	 */
	public function validateSalesOrderForm($postData)
	{
		$errors = array();
		try{
			
			$productId = $_POST['lstProduct'];
			$quantity = trim($_POST['txtProductQty']);
			if ($productId == 0){
				$errors[] = "Please select product.";
			}
			
			if ($quantity == '' || strlen($quantity) == 0 || !is_numeric($quantity)){
				$errors[] = "Please enter numeric order quantity.";
			}

		} catch (Exception $e){
			throw($e);
		}
		return $errors;
	}
}
?>